package com.windaka.elements.service;

import com.windaka.elements.dao.SysRoleMapper;
import com.windaka.elements.dao.SysUserMapper;
import com.windaka.elements.model.SysRole;
import com.windaka.elements.model.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * JdbcUserDetailsServiceImpl
 * @author song
 * @date 9:23 下午 2021/11/7
 * @param 
 * @return 
 * @other
**/
@Service
public class JdbcUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 传入的username会从这里校验
     * 校验数据库中是否有该用户 如果存在则完成权限的组装
     * @author song
     * @date 8:37 下午 2021/11/12
     * @param
     * @return
     * @other
    **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据username获取SysUser
        SysUser sysUser = SysUser
                .builder()
                .username(username)
                .build();
        sysUser = sysUserMapper.selectSysUser(sysUser);
        if (null != sysUser) {
            // 根据user获取role
            List<SysRole> roleList = sysRoleMapper.selectRoleByUser(sysUser);
            List<GrantedAuthority> authorityList = new ArrayList<>();
            // 组装用户有的权限信息 ROLE_ 前缀是框架固定的
            for (SysRole role : roleList) {
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role.getRoleName());
                authorityList.add(authority);
            }
            sysUser.setAuthorities(authorityList);
            return sysUser;
        }
        throw new UsernameNotFoundException("用户不存在!");
    }
}
